<template>
  <div class="divBox">
    <el-card class="box-card">
      <el-tabs v-model="activeName">
        <el-tab-pane label="基本信息" name="first">
          <el-form v-loading="saveLoading" ref="form" :model="form" :rules="rules" label-width="120px" @submit.native.prevent>
            <el-form-item label="照片：" prop="faceUrl">
              <el-upload
                  :disabled="isDisabled"
                  class="avatar-uploader"
                  action
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :http-request="handleUploadForm"
                  :headers="myHeaders"
                  :before-upload="beforeAvatarUpload">
                <img v-if="form.faceUrl" :src="imageUrl + form.faceUrl" class="avatar" alt="">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item label="姓名：" prop="tenantName">
              <el-input v-model="form.tenantName" placeholder="姓名" style="width: 50%" :disabled="isDisabled"
              ></el-input>
            </el-form-item>
            <el-form-item label="身份证号" prop="tenantIdCard">
              <el-input v-model="form.tenantIdCard" placeholder="身份证号"  style="width: 50%" :disabled="isDisabled"
              ></el-input>
            </el-form-item>
            <el-form-item label="联系方式" prop="tenantPhone">
              <el-input v-model="form.tenantPhone" placeholder="联系方式" style="width: 50%" :disabled="isDisabled"
              ></el-input>
            </el-form-item>
            <el-form-item label="工作单位" prop="tenantCompany">
              <el-input v-model="form.tenantCompany" placeholder="工作单位" style="width: 50%" :disabled="isDisabled"
              ></el-input>
            </el-form-item>
            <el-form-item label="实名状态" prop="faceAuthenticationTime">
              <el-select
                  v-model="currentFaceStatus"
                  placeholder="实名状态"
                  style="width: 50%"
                  :disabled="isDisabled"
                  @change="handleFaceStatusChange"
              >
                <el-option
                    v-for="item in faceOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>

            <!-- 新增家庭成员表格 -->
            <el-form-item label="家庭成员" prop="familyMembers">
              <el-table
                  :data="form.familyMembers"
                  border
                  style="width: 100%"
                  :disabled="isDisabled"
              >
                <el-table-column
                    prop="name"
                    label="姓名"
                    width="180">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.name" placeholder="请输入姓名"></el-input>
                  </template>
                </el-table-column>
                <el-table-column
                    prop="relationship"
                    label="与承租人关系"
                    width="180">
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.relationship" placeholder="请选择关系">
                      <el-option
                          v-for="item in relationshipOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                      </el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column
                    prop="company"
                    label="工作单位">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.company" placeholder="请输入工作单位"></el-input>
                  </template>
                </el-table-column>
                <el-table-column
                    prop="phone"
                    label="联系方式">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.phone" placeholder="请输入联系方式"></el-input>
                  </template>
                </el-table-column>
                <el-table-column
                    prop="isEmergency"
                    label="是否紧急联系人"
                    width="150">
                  <template slot-scope="scope">
                    <el-switch
                        v-model="scope.row.isEmergency"
                        active-color="#13ce66"
                        inactive-color="#ff4949">
                    </el-switch>
                  </template>
                </el-table-column>
                <el-table-column
                    label="操作"
                    width="150">
                  <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="danger"
                        @click="handleDeleteMember(scope.$index)"
                        :disabled="isDisabled">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div style="margin-top: 10px;">
                <el-button
                    type="primary"
                    size="small"
                    @click="handleAddMember"
                    :disabled="isDisabled">添加成员</el-button>
              </div>
            </el-form-item>


            <el-form-item>
              <el-button v-loading="saveLoading" element-loading-background="rgba(0, 0, 0, 0.3)" type="primary" :disabled="isDisabled"
                         @click="handlerSubmit" v-has-permi="['admin:lessee:save']">保存
              </el-button>
              <el-button @click="close" >取消</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="房屋信息" name="second">
          <House :id="form.id" :uniqueId="form.uniqueId" :tenantIdCard="form.tenantIdCard" :isDisabled="isDisabled" ></House>
        </el-tab-pane>
        <el-tab-pane label="租赁情况" name="third">
          <HouseSituation :id="form.id" :tenantIdCard="form.tenantIdCard"  :isDisabled="isDisabled"></HouseSituation>
        </el-tab-pane>
      </el-tabs>

    </el-card>

  </div>
</template>
<script>

import {upload} from "@/api/upload";
import {getToken} from "@/utils/auth";
import HouseSituation from "@/views/lessee/components/houseSituation.vue";
import House from "@/views/lessee/components/house.vue";
import {save, detail} from "@/api/lessee";

export default {
  components: {House, HouseSituation},
  data() {
    return {
      isDisabled: this.$route.params.isDisabled==='1'?true:false,
      activeName: 'first',
      form: {
        id: null,
        faceUrl:'',
        tenantIdCard:'',
        tenantName:'',
        tenantPhone:'',
        faceAuthenticationTime:'',
        tenantCompany:'',
        familyMembers: [] // 新增家庭成员数组
      },
      rules: {
        faceUrl: [{required: true, message: '请上传头像', trigger: ['blur']}],
        tenantIdCard: [{required: true, message: '请填写身份证号', trigger: ['blur']}],
        tenantName: [{required: true, message: '请填写姓名', trigger: ['blur']}],
        tenantPhone: [{required: true, message: '请填写联系电话', trigger: ['blur']}],
      },
      saveLoading: false,
      formLoading: false,
      faceOptions: [
        { value: '已实名', label: '已实名' },
        { value: '未实名', label: '未实名' }
      ],
      myHeaders: {"token": getToken()},
      imageUrl: '',
      relationshipOptions: [
        { value: '配偶', label: '配偶' },
        { value: '子女', label: '子女' },
        { value: '父母', label: '父母' },
        { value: '兄弟姐妹', label: '兄弟姐妹' },
        { value: '其他亲属', label: '其他亲属' },
        { value: '其他', label: '其他' }
      ],
    }
  },
  computed: {
    // 根据faceAuthenticationTime的值计算当前显示状态
    currentFaceStatus: {
      get() {
        return this.form.faceAuthenticationTime ? '已实名' : '未实名'
      }
    }
  },
  mounted() {
    this.imageUrl = process.env.VUE_APP_IMAGE_URL
    if (this.$route.params.id) {
      this.getDetail();
    }
  },

  methods: {
    getDetail() {
      // 这里可以添加获取房屋详情的逻辑，发送API请求获取数据
      this.saveLoading = true;
      detail(this.$route.params.id).then((res) => {
        this.form = {
          ...res,
          familyMembers: res.familyMembers || [] // 确保有familyMembers数组
        };
        this.close();
      }).finally(() => {
        this.saveLoading = false
      })

    },
    handlerSubmit() {
      if (this.saveLoading) {
        return
      }
      this.$refs.form.validate(valid => {
        if (!valid) return;
        this.saveLoading = true;
        save(this.form).then(() => {
          this.$message.success('保存成功');
          this.close();
        }).finally(() => {
          this.saveLoading = false
        })
      })
    },
    handleAvatarSuccess(res, file) {
      this.form.faceUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG、PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    handleUploadForm(param) {
      const formData = new FormData();
      //0=>maintain 全部
      formData.append("file", param.file);
      let loading = this.$loading({
        lock: true,
        text: "上传中，请稍候...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      upload(formData)
          .then((res) => {
            this.form.faceUrl = res
            //图片上传接口 后期调用
            loading.close();
            this.$message.success("上传成功");
          }).catch((res) => {
        loading.close();
      });
    },
    handleFaceStatusChange(val) {
      if (val === '已实名') {
        this.form.faceAuthenticationTime = new Date().toISOString() // 设置为当前ISO时间
      } else {
        this.form.faceAuthenticationTime = null // 设置为null
      }
    },
    close() {
      this.$emit('hideEditDialog');
    },
    // 新增家庭成员
    handleAddMember() {
      this.form.familyMembers.push({
        name: '',
        relationship: '',
        company: '',
        phone: '',
        isEmergency: false
      });
    },
    // 删除家庭成员
    handleDeleteMember(index) {
      this.$confirm('确认删除该家庭成员吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form.familyMembers.splice(index, 1);
        this.$message.success('删除成功');
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },



  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}



::v-deep .el-textarea .el-input__count {
  position: absolute;
  right: -50px;
  bottom: 0;
  background: transparent;
}
</style>
